package com.beiding.render;

import jdk.nashorn.api.scripting.ScriptObjectMirror;

import java.util.*;

public class ScriptHelper {
    public static final ScriptHelper INSTANCE = new ScriptHelper();

    public Object[] argumentsToArray(ScriptObjectMirror ps) {
        Object[] r = new Object[ps.size()];
        for (int i = 0; i < ps.size(); i++) {
            r[i] = ps.getSlot(i);
        }
        return r;
    }

    public static void statementHandler(RenderContext _this, String name, Handler handler) {

        Map data = new HashMap();

        //为什么会是null
        data.put("__script_help", ScriptHelper.INSTANCE);
        data.put("__" + handler.name(), handler);

        String id = "__this_" + ContentUtils.createId();

        data.put(id, _this);   //自己作为自己的参数

        //放入数据
        // data.put("_this", data);

        ScriptUtils.exe(data, id + "." + name + " = function (){return __" + handler.name() + ".handle(" + id + ",__script_help.argumentsToArray(arguments));}");

    }

    public static void moveGlobal(Map data) {

        Map remove = (Map) data.remove("nashorn.global");
        if (remove != null) {
            data.putAll(remove);
        }
    }


    //分段处理

    private static class Subsection {
        //当前分段变量
        String key;

        //是否是个数组
        boolean isArray = false;

        //可能是多维的数组
        int[] inds;
    }

    private static List<Subsection> splitKey(String key) {
        String[] split = key.split("\\.");
        List<Subsection> subsections = new ArrayList<>();
        for (String s : split) {
            String k = s.trim();
            if (k.equals("")) {
                throw new RuntimeException("错误的key:" + key);
            }


            int i = k.indexOf('[');
            if (i == -1) {
                Subsection subsection = new Subsection();
                subsection.key = k;
                subsections.add(subsection);

            } else {

                if (!k.endsWith("]")) {
                    throw new RuntimeException("错误的key:" + key);
                }

                String arr = k.substring(i + 1, k.length() - 1);

                String[] strings = arr.split("]\\[");

                int[] ints = new int[strings.length];
                try {
                    for (int j = 0; j < strings.length; j++) {
                        ints[j] = Integer.valueOf(strings[j]);
                    }
                } catch (Exception ignore) {
                    throw new RuntimeException("错误的key:" + key);
                }

                k = k.substring(0, i);
                if (k.equals("")) {
                    throw new RuntimeException("错误的key:" + key);
                }
                Subsection subsection = new Subsection();
                subsection.key = k;
                subsection.isArray = true;
                subsection.inds = ints;
                subsections.add(subsection);
            }

        }

        if (subsections.size() == 0) {
            throw new RuntimeException("错误的key:" + key);
        }

        return subsections;
    }

    public List createList() {
        return new ArrayList();
    }


    //TODO 是否有必要 将创建策略开放
    public void listMakeSureSize(List list, int min) {

        if (list.size() < min) {
            int k = min - list.size();
            for (int i = 0; i < k; i++) {
                list.add(null);
            }
        }
    }

    public Map createMap() {
        return new HashMap();
    }


    private static String buildE(String k, boolean arr, int index) {
        return "if(" + k + "==null" + "){" + k + "=" + (arr ? "__script_helper__.createList()" : "__script_helper__.createMap()") + "};" + (arr ? "__script_helper__.listMakeSureSize(" + k + "," + (index + 1) + ")" : "");
    }

    public static void set(Map data, String key, Object value) {

        data.put("__script_helper__", INSTANCE);

        List<Subsection> subsections = splitKey(key);
        Iterator<Subsection> iterator = subsections.iterator();

        List<String> sNodes = new LinkedList<>();
        StringBuilder builder = new StringBuilder();
        Subsection next = iterator.next();
        if (next.isArray) {
            builder.append(next.key);
            sNodes.add(buildE(builder.toString(), true, next.inds[0]));
            int ui = next.inds.length - 1;
            for (int i = 0; i < ui; i++) {
                builder.append('[').append(next.inds[i]).append(']');
                sNodes.add(buildE(builder.toString(), true, next.inds[i + 1]));
            }
            builder.append('[').append(next.inds[ui]).append(']');
            sNodes.add(buildE(builder.toString(), false, -1));
        } else {
            builder.append(next.key);
            sNodes.add(buildE(builder.toString(), false, -1));
        }

        while (iterator.hasNext()) {
            next = iterator.next();
            if (next.isArray) {
                builder.append('.').append(next.key);
                sNodes.add(buildE(builder.toString(), true, next.inds[0]));
                int ui = next.inds.length - 1;
                for (int i = 0; i < ui; i++) {
                    builder.append('[').append(next.inds[i]).append(']');
                    sNodes.add(buildE(builder.toString(), true, next.inds[i + 1]));
                }
                builder.append('[').append(next.inds[ui]).append(']');
                sNodes.add(buildE(builder.toString(), false, -1));

            } else {
                builder.append('.').append(next.key);
                sNodes.add(buildE(builder.toString(), false, -1));
            }
        }

        //  System.out.println(map);

        sNodes.set(sNodes.size() - 1, builder.toString() + "=__theTargetValue");

        data.put("__theTargetValue", value);
        for (String sNode : sNodes) {

            //TODO 如果是数组应该先进行扩容

            ScriptUtils.exe(data, sNode);
        }
        data.remove("__theTargetValue");
        data.remove("__script_helper__");
    }

    public static void main(String[] args) {

        List list = new ArrayList();
        list.set(0, "");

    }

}
